import Editor from "../../../components/question-base/editor.vue";
import TestSpecificationDialog from "../test-specification-dialog/index.vue";
import SelectGroupsBase from "../select-groups-base/index.vue";
import SelectGroupsTag from "../select-groups-tag/index.vue";
import ErrorView from "./comp/error-view.vue";
import ErrorDialog from "./comp/error-dialog.vue";
import SubmitDialog from "./comp/submit-dialog.vue";
import SuccessDialog from "./comp/success-dialog.vue";
import TestPaperPackageDialog from "./comp/test-paper-package-dialog.vue";
import questionApi from "@rc/apis/rc/question.mjs";
import RepeatDialog from "./comp/repeat-dialog.vue";
import RepeatProcessDialog from "./comp/repeat-process-dialog.vue";

export default {
    name: "add-batch",
    components: {
        Editor,
        TestSpecificationDialog,
        ErrorView,
        SelectGroupsBase,
        SelectGroupsTag,
        ErrorDialog,
        SubmitDialog,
        SuccessDialog,
        TestPaperPackageDialog,
        RepeatDialog,
        RepeatProcessDialog,
    },
    computed: {
        //点击上传是否可用
        isCanUpload() {
            return !this.basicInfo.subjectId;
        },
        //识别正确的数量
        rightNum(){
            let count = 0;
            this.questionRecognizeList.forEach(questionTypes=> {
                const questionTypeDataList = questionTypes.questionTypeDataList || [];
                questionTypeDataList.forEach((question)=>{
                    if(question.smallQuestionList && question.smallQuestionList.length) {
                        count += question.smallQuestionList.length;
                    } else {
                        count += 1;
                    }
                });
              });
            return count;
        },
        // 基础信息回显
        basicDetail(){
            let projectId = this.$route.query.projectId ? [this.$route.query.projectId]:[];
            let subjectId = this.$route.query.projectId ? this.$route.query.subjectId:"";
            return{
                projectId:this.entrance ==='qb' ?projectId :[],
                subjectId:this.entrance ==='qb' ?subjectId:""
            };
        },
        // 基础表单项禁用
        disablePropList(){
            return this.entrance ==='qb' ? ['projectId','subjectId'] :[];
        }
    },
    data() {
        return {
            combinedType: ["A", "CF", "L", "C"], //组合题型
            placeholderText:
                "<p>1.支持将Word文档的试题导入，一次建议导入200题以下</p><p>2.支持将Word、TXT中的试题复制后粘贴在编辑区</p><p>3.支持在编辑区直接录入或修改试题</p><p>4.查看右上角【查看格式规范】，按照格式要求录入试题</p>", // 富文本提示
            editorHtml: "", // 编辑内容
            isShowTestSpecificationDialog: false, //试题录入规范
            isShowPlaceholder: true, // 是否展示右侧的提示
            disabled: true, //上传按钮是否禁用
            rulesPropList: ["projectId", "subjectId"],
            recognizeNumber: {
                //试题识别结果数信息
                totalNum: 0, //识别试题总数
                errorNum: 0, //识别试题错误数
                repeatNum: 0
            },
            questionRecognizeList: [], //识别的试题集合
            questionRecognizeErrorList: [], //识别的试题集合
            errorList: [],
            basicInfo: {},
            isUploadLoading: false,
            isShowErrorDialog: false,//显示识别错题弹窗
            isShowSubmitDialog:false,//显示提交确认框
            isSubmitLoading:false,//按钮loading
            isSubmitLoadingEdit:false,//按钮提交并加载中
            isShowSuccessDialog:false,//提交成功弹窗提示
            uploadText:'点击上传',
            timer:null,//防抖定时器
            isShowRepeatDialog: false,
            questionRepeatMessageList: [],
            isShowRepeatProcessDialog: false,
            questionRepeatList: [],
            questionRepeatIdList: [],
            entrance: "", // 来源入口 qb：题库
            questionPackageId: "", // 试卷包标识
            repeatResourceIdList: [],
            repeatResourceUpdateList: [],
            repeatResourceUpdateBaseList: [],
        };
    },
    created(){
        this.$nextTick(()=>{
            this.entrance = this.$route.query.entrance || '';
        });
    },
    methods: {
        /**
         * 下载模板
         */
        download() {
            questionApi.getQuestionTemplateUrl({
                success: (result) => {
                    let wordUrl = result && result.wordUrl ? result.wordUrl :'';
                    nlapp.FileUtil.download(wordUrl);
                }
            });
        },
        /**
         * 清空内容
         */
        handleClear() {
            this.$refs.editorRef.html='';
            this.editorHtml='';
            this.recognizeNumber = {
                totalNum: 0,
                errorNum: 0,
                repeatNum: 0,
            };
            this.questionRecognizeList = [];
            this.questionRecognizeErrorList = [];
            this.isShowPlaceholder = true;
            this.questionRepeatList = [];
        },
        /**
         * 识别内容
         */
        async handleIdentify() {
            const html = this.$refs.editorRef.api_getHtml();
            if (!html) {
                this.$message.warning("请先上传或录入试题内容");
                return;
            }
            const result = await this.$refs.baseRef.api_validateField();
            if (result) {
                this.onFileUploadSuccessBatch();
            }
        },
        resetUploadButton(){
            this.$refs.batchUploadBtn.reset();
        },
        // 上传识别试题内容
        onFileUploadSuccessBatch(fileInfo) {

            let params = {};
            if (fileInfo) {
                params.action = "W"; //文档上传
                params.filePath = fileInfo.filePath;
            } else {
                params.action = "C"; //富文本
                params.importContent = this.$refs.editorRef.api_getStringList();
            }
            this.isUploadLoading = true;
            this.errorList=[];
            //文档上传先获取htmlContent再次调用接口识别试题，富文本直接识别试题
            this.recognizeQuestion(params,()=>{
                setTimeout(()=>{//识别文档上传后的htmlContent信息
                    this.uploadText="重新上传";
                    this.recognizeQuestion({
                        action:"C",
                        importContent:this.$refs.editorRef.api_getStringList()
                    });
                },1000);
            });

        },
        /**
         * 识别信息
         * @param {*} params 入参
         * @param {*} callback 回调函数文档 上传使用
         */
        recognizeQuestion(params,callback){
            questionApi.recognizeQuestion({
                data: {
                    ...params
                },
                success: (data) => {
                    if( params.action==='W'){//文档上传获取成功之后，再次调用识别接口识别html信息
                        this.editorHtml = data.htmlContent;
                        callback && callback();
                    } else {
                        this.recognizeNumber = data.recognizeNumber;
                        this.questionRecognizeList = data.questionRecognizeList;
                        this.questionRecognizeErrorList = data.questionRecognizeErrorList;
                        const d = Date.now();
                        this.questionRepeatMessageList = data.questionRepeatMessageList.map((item, index) => {
                            return {
                                id: `${d}-${index}`,
                                content: item,
                            };
                        });

                        if (this.recognizeNumber.errorNum) {
                            this.isShowPlaceholder = false;
                            this.isShowErrorDialog = true;
                            this.getErrorList();
                        } else {
                            this.isShowPlaceholder = true;
                        }
                    }
                },
                complete: () => {
                    if(params.action==='C'){
                        this.isUploadLoading = false;
                    }
                }
            });
        },
        //筛选错误的题
        getErrorList() {
            this.errorList = [];
            //将相同错误题型整合到一个列表中
            let questionErrorList = [];
            this.questionRecognizeErrorList.forEach((item)=>{
                let index = questionErrorList.findIndex(question=>question.questionType===item.questionType);
                if(index!==-1){
                    questionErrorList[index].questionTypeDataList.push(...item.questionTypeDataList);
                } else {
                    questionErrorList.push(item);
                }
            });

            questionErrorList.forEach((question) => {
                const { questionSeq, questionType, questionTypeName, questionTypeDataList } = question;
                let questionItem = {
                    questionSeq,
                    questionType,
                    questionTypeName,
                    errorNum:0
                };
                questionItem.questionTypeDataList = [];
                if (this.combinedType.includes(questionType)) {
                    //组合题
                    const list = question.questionTypeDataList;
                    list.forEach((combinedQuestion) => {
                        let cQuestion = {
                            ...combinedQuestion,
                            questionType:question.questionType,
                            index:combinedQuestion.questionSeq
                        };

                        cQuestion.smallQuestionList = [];
                        combinedQuestion.smallQuestionList.forEach((sub, subIndex) => {
                            if (sub.isError) {
                                questionItem.errorNum++;
                            }
                            cQuestion.smallQuestionList.push({
                                ...sub,
                                index: cQuestion.index + "." + (subIndex + 1)
                            });
                        });
                        if(cQuestion.isError){//如果大题错误，错误数量直接计算为小题的数量
                            questionItem.errorNum = combinedQuestion.smallQuestionList.length;
                        }
                        //当题本身错误或者有小题错误
                        if(cQuestion.isError || combinedQuestion.smallQuestionList.some(sub=>sub.isError)){
                            questionItem.questionTypeDataList.push(cQuestion);
                        }
                    });
                } else {
                    //普通题
                    questionTypeDataList.forEach((item) => {
                        if (item.isError) {
                            questionItem.errorNum++;
                            questionItem.questionTypeDataList.push({
                                ...item,
                                index: item.questionSeq
                            });
                        }
                    });
                }
                if (questionItem.questionTypeDataList.length) {
                    this.errorList.push(questionItem);
                }
            });
        },
        //基本属性变化
        onBasicChange(basicInfo) {
            this.basicInfo = basicInfo;
        },
        // 标签属性变化
        onTagChange(basicInfo) {
            this.tagInfo = basicInfo;
        },
        replaceImg(content){
            let imgList = [];
            content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, function (match, capture) {
                imgList.push(capture); // capture图片地址 img标签中src内容   match // img标签整体
            });
            return imgList;
        },
        //获取上传的图片
        getImgList(list){
            let imgList = [];
            list.forEach(question=>{
                for(let key in question) {
                    if(key==='optionList' && question.optionList) {
                        question.optionList.forEach(option=>{
                            const imgs = this.replaceImg(option.answerOption);
                            imgList.push(...imgs);
                        });
                    }
                    if(key==='questionAnswerParse'||key==='questionTitle'){
                        const imgs = this.replaceImg(question[key]);
                        imgList.push(...imgs);
                    }
                    if (this.combinedType.includes(question.questionType)){
                        const imgs = this.getImgList(question.smallQuestionList);
                        imgList.push(...imgs);
                    }
                }
            });
            return imgList;
        },
        //批量添加试题
        submit(callback, repeatCallback, repeatResourceIds = []){
            // 入参题型顺序
            let questionTypeList = [];
            //  入参-试题列表
            let rcResourceQuestionPostVoList = [];
            let questionList = [];
            const noRepeatIdList = this.questionRepeatIdList.map(({ operatedResourceId }) => operatedResourceId);
            //过滤出所有正确的题
            this.questionRecognizeList.forEach(questionTypes => {
               const questionTypeDataList = JSON.parse(JSON.stringify(questionTypes.questionTypeDataList));
               questionList.push(...questionTypeDataList);
               //合并题型顺序
               const index = questionTypeList.findIndex(questionType => questionType === questionTypes.questionType);
               const ext = questionTypeDataList.every(({ resourceId } ) => noRepeatIdList.includes(resourceId));
               if (index === -1 && ext === false){
                  questionTypeList.push(questionTypes.questionType);
               }
            });
            questionList = questionList.filter(({ resourceId }) => noRepeatIdList.includes(resourceId) === false);
            const getQuestion=(question)=>{
                delete question.isError;
                delete question.errorInfo;
                delete question.isShowChapter;
                delete question.isShowKnowledge;
                delete question.isShowLabel;
                delete question.isProcess;
                delete question.isChecked;
                delete question.opType;

                const {
                    projectId,
                    projectName,
                    subjectId,
                    subjectName,
                    chapterList,
                    questionDeveloperId,
                    questionDeveloperName,
                    knowledgeList
                } = this.$refs.baseRef.api_result();
                const {applicableYear,labelList,areaList} = this.$refs.tagRef.api_result();;
                question = {
                    ...question,
                    projectId:projectId.length?projectId[projectId.length-1]:'',
                    projectName,
                    subjectId,
                    subjectName,
                    chapterList,
                    questionDeveloperId,
                    questionDeveloperName,
                    knowledgeList,
                    applicableYear,
                    labelList: labelList?labelList.filter(label=>label.labelDetailId):[],
                    areaList
                };
                // 除简答题外其他题型也返回了这些字段，前端去掉类型判断  ---特殊处理 如果智能阅卷关键词/关键词得分权重为空则不传这两个字段
                let props = ['questionKeywords','questionScoreWeight'];
                props.forEach((prop)=>{
                    if(question[prop] === '' || question[prop] === null || question[prop] === undefined){
                        delete question[prop];
                    }
                });
                return question;
            };
            rcResourceQuestionPostVoList = questionList.map((question)=>{
                question = getQuestion(question);
                if(this.combinedType.includes(question.questionType)){
                    let smallQuestionList = [];
                    question.smallQuestionList.forEach((smallQuestion)=>{
                        smallQuestion = getQuestion(smallQuestion);
                        delete smallQuestion.smallQuestionList;
                        delete smallQuestion.isShowChapter;
                        delete smallQuestion.isShowKnowledge;
                        delete smallQuestion.isShowLabel;
                        delete smallQuestion.isProcess;
                        delete smallQuestion.isChecked;
                        delete smallQuestion.opType;
                        smallQuestionList.push(smallQuestion);
                    });
                    question.smallQuestionList = smallQuestionList;
                } else { //删除子题中的smallQuestionList属性
                    delete  question.smallQuestionList;
                }
                return question;
            });
            if (rcResourceQuestionPostVoList.length <= 0 && this.entrance !== 'qb') {
                callback && callback({});
                return;
            }
            //提取所有的图片路径
            let imgList = this.getImgList(rcResourceQuestionPostVoList);
            let createQuestionPackage =false;
            if(this.entrance ==='qb'){
                createQuestionPackage = true;
            }
            questionApi.batchAddQuestion({
                data: {
                    createQuestionPackage: createQuestionPackage, // 是否生成试题包
                    rcResourceQuestionPostVoList,
                    filePathList: Array.from(new Set(imgList)),
                    questionTypeList,
                    repeatResourceIds: repeatResourceIds,
                },
                success: (data) => {
                    const { questionRepeatResponseVos = [] } = data;
                    console.warn('questionRepeatResponseVos', questionRepeatResponseVos);
                    this.questionPackageId = data && data.questionPackageId ? data.questionPackageId :''; // 试卷包标识
                    if (questionRepeatResponseVos.length <= 0) {
                        this.$message.success('批量添加成功');
                        callback && callback(data);
                    } else {
                        this.questionRepeatIdList.push(...questionRepeatResponseVos);
                        repeatCallback && repeatCallback(questionRepeatResponseVos);
                    }
                },
                complete: () => {
                    this.isSubmitLoading = false;
                    this.isSubmitLoadingEdit = false;
                },
                error: ({ msg }) => {
                    MsgBox.alert(msg);
                },
                fail: ({ msg }) => {
                    MsgBox.alert(msg);
                },
            });
        },
        /**
		 * 打开新页面
		 * @param {Object} routerOption 路由配置项
		 */
		openBlankPage(routerOption) {
			let routeData = this.$router.resolve(routerOption);
			window.open(routeData.href, "_blank");
		},
        //提交并补充
        onSubmitEdit() {
            // 在#提交提示#弹窗点击【提交】/【提交并补充信息】时继续验证本次导入试题与试试题库启用状态的已有试题之间是否有重复的，如果有则弹出#重复试题处理#弹窗
            this.debounce(() => {
                this.isSubmitLoadingEdit = true;
                this.submit((data) => {
                    //关闭提交弹窗
                    this.isShowSubmitDialog = false;

                    if(this.entrance ==='qb'){
                        this.$refs.refTestPaperPackage.open(this.questionPackageId); // 试卷包
                    } else {
                         //显示提交成功弹窗
                        this.isShowSuccessDialog = true;
                    }
                    let questionBatchResponseVos = data && data.questionBatchResponseVos && data.questionBatchResponseVos.length ? data.questionBatchResponseVos: [];
                    localStorage.setItem('rc-questionIds',JSON.stringify(questionBatchResponseVos));
                    this.openBlankPage({
                        path: "/rc/questions-preview",
                        query: {
                            pageType: 'edit',
                            dataGetType: 'localStorageBase',
                            localStorageKey: 'rc-questionIds'
                        }
                    });
                }, (repeatList) => {
                    // 有重复
                    this.isShowSubmitDialog = false;
                    this.submitType = 1;
                    this.handleRepeat(repeatList);
                });
            }, 1000);
        },
        //函数防抖
        debounce(callback, wait = 0) {
            if (!this.timer) {
                callback();
                this.timer = setTimeout(() => {
                    clearTimeout(this.timer);
                    this.timer = null;
                }, wait);
            }
        },
        /**
         * 弹窗内提交
         */
        onSubmit() {
            // 在#提交提示#弹窗点击【提交】/【提交并补充信息】时继续验证本次导入试题与试试题库启用状态的已有试题之间是否有重复的，如果有则弹出#重复试题处理#弹窗
            this.debounce(() => {
                this.isSubmitLoading = true;
                this.submit(() => {
                    // 生成试卷包
                    if (this.entrance === 'qb') {
                        this.isShowSubmitDialog = false;
                        this.$refs.refTestPaperPackage.open(this.questionPackageId);
                    } else {
                        this.goBackList();
                    }
                }, (repeatList) => {
                    // 有重复
                    this.isShowSubmitDialog = false;
                    this.submitType = 0;
                    this.handleRepeat(repeatList);
                });
            }, 1000);
        },
        handleRepeat(repeatList) {
            const t = [];
            const d = Date.now();

            const { chapterList, knowledgeList } = this.$refs.baseRef.api_result();
            const { applicableYear, labelList, areaList } = this.$refs.tagRef.api_result();;
            this.questionRecognizeList.flatMap(({ questionTypeDataList }) => questionTypeDataList).forEach((item) => {
                item.chapterList = chapterList;
                item.knowledgeList = knowledgeList;
                item.applicableYear = applicableYear;
                item.labelList = labelList;
                item.areaList = areaList;
                item.smallQuestionList.forEach((citem) => {
                    citem.chapterList = chapterList;
                    citem.knowledgeList = knowledgeList;
                    citem.applicableYear = applicableYear;
                    citem.labelList = labelList;
                    citem.areaList = areaList;
                });
            });

            repeatList.forEach(({ operatedResourceId, repeatResourceId }, index) => {
                const c = this.questionRecognizeList.find(({ questionTypeDataList }) => questionTypeDataList.some(({ resourceId }) => operatedResourceId === resourceId));
                const tc = t.find(({ questionType }) => questionType === c.questionType) || (t.push({ id: `${d} - ${index}`, questionTotal: 0, questionType: c.questionType, questionTypeDataList: [], questionTypeName: c.questionTypeName }), t[t.length - 1]);
                const q = c.questionTypeDataList.find(({ resourceId }) => operatedResourceId === resourceId);
                q.repeatResourceId = repeatResourceId;
                tc.questionTypeDataList.push(q);
                ++tc.questionTotal;
            });
            this.isShowRepeatProcessDialog = true;
            this.questionRepeatList = t;
        },
        goBackList(){
            nlapp.TabManager.closeBack(`/rc/questions/list`);
        },
        async validateQuestion(callback) {
            const validateBase = await this.$refs.baseRef.api_validateField();
            if (!validateBase) {
                //校验通过
                this.$message.warning("项目、科目不能为空");
                return;
            }
            const { totalNum, errorNum, repeatNum } = this.recognizeNumber;
            if (totalNum - errorNum === 0) {
            	this.$message.warning("没有识别成功的试题");
            	return;
            }
            if (repeatNum > 0) {
                return this.isShowRepeatDialog = true;
            }
            if (totalNum - errorNum > 300) {
            	this.$message.warning("试题数量过多,请分开上传");
            	return;
            }
            callback && callback();
        },
        // 提交信息
        async api_submit() {
            this.validateQuestion(() => {
                this.questionRepeatIdList.splice(0, this.questionRepeatIdList.length);
                this.repeatResourceIdList.splice(0, this.repeatResourceIdList.length);
                this.repeatResourceUpdateList.splice(0, this.repeatResourceUpdateList.length);
                this.repeatResourceUpdateBaseList.splice(0, this.repeatResourceUpdateBaseList.length);

                this.isShowSubmitDialog = true;
            });
        },
        // 预览试题
        api_preview() {
            this.validateQuestion(() => {
                let questionList = [];
                this.questionRecognizeList.forEach((item)=>{
                    let index = questionList.findIndex(question=>question.questionType===item.questionType);
                    if(index!==-1){
                        const questionTypeDataList = JSON.parse(JSON.stringify(item.questionTypeDataList));
                        questionList[index].questionTypeDataList.push(...questionTypeDataList);
                    } else {
                        const questionTypeDataList = JSON.parse(JSON.stringify(item));
                        questionList.push(questionTypeDataList);
                    }
                });
                localStorage.setItem('rc-questionList',JSON.stringify(questionList));
                this.openBlankPage({
                    path:"/rc/questions-preview",
                    query:{
                        pageType: 'preview',
                        dataGetType: 'localStorageAll',
                        localStorageKey: 'rc-questionList'
                    }
                });

            });
        },
        handleRepeatSuccess({ abandonList, updateList, updateBaseList }) {
            console.warn('handleRepeatSuccess', abandonList, updateList, updateBaseList);
            console.warn('handleRepeatSuccess-submitType', this.submitType);
            const ar = updateList.map(({ repeatResourceId }) => repeatResourceId).concat(updateBaseList.map(({ repeatResourceId }) => repeatResourceId));
            this.repeatResourceIdList.push(...ar);
            this.repeatResourceUpdateList.push(...updateList);
            this.repeatResourceUpdateBaseList.push(...updateBaseList);

            if (this.submitType) {
                this.isSubmitLoadingEdit = true;
                this.submit(({ questionBatchResponseVos = [] }) => {
                    Promise.all([this.rewriteSubmit(this.repeatResourceUpdateList, 'all'), this.rewriteSubmit(this.repeatResourceUpdateBaseList, 'base')]).then(() => {
                        this.isShowRepeatProcessDialog = false;
                        this.isShowSubmitDialog = false;
                        if(this.entrance ==='qb'){
                            this.$refs.refTestPaperPackage.open(this.questionPackageId); // 试卷包
                        } else {
                             //显示提交成功弹窗
                            this.isShowSuccessDialog = true;
                        }
                        localStorage.setItem('rc-questionIds', JSON.stringify(questionBatchResponseVos));
                        this.openBlankPage({
                            path: "/rc/questions-preview",
                            query: {
                                pageType: 'edit',
                                dataGetType: 'localStorageBase',
                                localStorageKey: 'rc-questionIds'
                            }
                        });
                    }).finally(() => {
                        this.isSubmitLoadingEdit = false;
                    });
                }, (repeatList) => {
                    this.isSubmitLoadingEdit = false;
                    this.isShowSubmitDialog = false;
                    this.submitType = 1;
                    this.handleRepeat(repeatList);
                }, this.repeatResourceIdList);
            } else {
                this.isSubmitLoading = true;
                this.submit(() => {
                    Promise.all([this.rewriteSubmit(this.repeatResourceUpdateList, 'all'), this.rewriteSubmit(this.repeatResourceUpdateBaseList, 'base')]).then(() => {
                        this.isShowRepeatProcessDialog = false;
                        // 生成试卷包
                        if (this.entrance === 'qb') {
                            this.$refs.refTestPaperPackage.open(this.questionPackageId);
                        } else {
                            this.goBackList();
                        }
                    }).finally(() => {
                        this.isSubmitLoading = false;
                    });
                }, (repeatList) => {
                    this.isSubmitLoading = false;
                    this.isShowSubmitDialog = false;
                    this.submitType = 0;
                    this.handleRepeat(repeatList);
                }, this.repeatResourceIdList);
            }
        },
        rewriteSubmit(questionUpdateList = [], type) {
            let questionTypeList = [];
            let rcResourceQuestionPostVoList = [];
            let questionList = [];
            const updateIdList = questionUpdateList.map(({ resourceId }) => resourceId);
            this.questionRecognizeList.forEach(questionTypes => {
               const questionTypeDataList = JSON.parse(JSON.stringify(questionTypes.questionTypeDataList));
               questionList.push(...questionTypeDataList);
               const index = questionTypeList.findIndex(questionType => questionType === questionTypes.questionType);
               const ext = questionTypeDataList.length > 0 && questionTypeDataList.every(({ resourceId } ) => updateIdList.includes(resourceId));
               if (index === -1 && ext === true) {
                  questionTypeList.push(questionTypes.questionType);
               }
            });

            questionList = questionList.filter(({ resourceId }) => updateIdList.includes(resourceId));
            if (questionList.length <= 0) {
                return Promise.resolve();
            }
            const getQuestion = (question) => {
                delete question.isError;
                delete question.errorInfo;
                delete question.isShowChapter;
                delete question.isShowKnowledge;
                delete question.isShowLabel;
                delete question.isProcess;
                delete question.isChecked;
                delete question.opType;

                const {
                    projectId,
                    projectName,
                    subjectId,
                    subjectName,
                    chapterList,
                    questionDeveloperId,
                    questionDeveloperName,
                    knowledgeList,
                } = this.$refs.baseRef.api_result();
                const { applicableYear, labelList, areaList } = this.$refs.tagRef.api_result();;
                question = {
                    ...question,
                    projectId:projectId.length?projectId[projectId.length-1]:'',
                    projectName,
                    subjectId,
                    subjectName,
                    chapterList,
                    questionDeveloperId,
                    questionDeveloperName,
                    knowledgeList,
                    applicableYear,
                    labelList: labelList ? labelList.filter(label => label.labelDetailId) : [],
                    areaList,
                };
                const props = ['questionKeywords','questionScoreWeight'];
                props.forEach((prop)=>{
                    if (question[prop] === '' || question[prop] === null || question[prop] === undefined){
                        delete question[prop];
                    }
                });
                return question;
            };
            rcResourceQuestionPostVoList = questionList.map((question)=>{
                question = getQuestion(question);
                if (this.combinedType.includes(question.questionType)) {
                    let smallQuestionList = [];
                    question.smallQuestionList.forEach((smallQuestion) => {
                        smallQuestion = getQuestion(smallQuestion);
                        delete smallQuestion.smallQuestionList;
                        delete smallQuestion.isShowChapter;
                        delete smallQuestion.isShowKnowledge;
                        delete smallQuestion.isShowLabel;
                        delete smallQuestion.isProcess;
                        delete smallQuestion.isChecked;
                        delete smallQuestion.opType;

                        smallQuestionList.push(smallQuestion);
                    });
                    question.smallQuestionList = smallQuestionList;
                } else {
                    delete  question.smallQuestionList;
                }

                const u = questionUpdateList.find(({ resourceId }) => resourceId === question.resourceId);
                question.repeatResourceId = u.repeatResourceId;

                return question;
            });
            const imgList = this.getImgList(rcResourceQuestionPostVoList);
            return questionApi.batchRepeatRewrite({
                repeatQuestionPutVos: rcResourceQuestionPostVoList,
                filePathList: Array.from(new Set(imgList)),
                questionTypeList,
                rewriteType: type.slice(0, 1).toUpperCase(),
            });
        },
    }
};
